﻿using Entity;
using ServiceCore;
using ServiceCore.Tool.AliFace;
using ServiceCore.Tool.JD_Pay;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Customer.Bussiness_Service
{
    public interface Iali_mch_settlement_service
    {
        ResultObjModel temp_in_data();

        ResultObjModel start_run_ali();
         
    }
    public class ali_mch_settlement_service : Iali_mch_settlement_service
    {
        private readonly IFacePay _face_service;
        private readonly IToole_DI _tool;

        public ali_mch_settlement_service(IFacePay Face_service, IToole_DI Tool)
        {
            _face_service = Face_service;
            _tool = Tool;
        }
        /// <summary>
        /// 批量数据入驻
        /// </summary>
        /// <returns></returns>
        public ResultObjModel temp_in_data() {
            return CoreStartDo.ResultAction(result =>
            {
                string sql_mast = "select id,SN,BaseUserId from mch where datalength(SN) = 40 and BaseUserId > '0' and BaseUserId<>'1421' and BaseUserId<> 'rk_test' and BaseUserId<>'rk'";
                List<Mch> mchlist = _tool.di_db.Get_rk_List<Mch>(sql_mast, sql_mast).ToList();
                List<JdmerchantBase> jdinfo = _tool.di_db.Get_rk47_List<JdmerchantBase>("select * from JdmerchantBase where baseuserid in @baseuserids", new { baseuserids = mchlist.Select(s => s.BaseUserId).Distinct().ToArray() }).ToList();
                int successcount = 0;
                int errorcount = 0;
                foreach (var item in mchlist)
                {
                    var mchitem = _tool.di_db.Get_rk_List<mch_settlement>("select * from mch_settlement where mchid=@mchid", new { mchid = item.Id }).FirstOrDefault();
                    if (mchitem == null)
                    {
                        mch_settlement mchinfo = new mch_settlement();
                        mchinfo.mchid = item.Id;
                        mchinfo.addtime = DateTime.Now;
                        mchinfo.baseuserid = item.BaseUserId;
                        try
                        { 
                            int ref_provice = 0;
                            int ref_city = 0;
                            int ref_area = 0;
                            string address = ""; 
                            get_address(jdinfo.Where(s => s.baseuserid == item.BaseUserId).FirstOrDefault(), ref ref_provice, ref ref_city, ref ref_area, ref address);
                            mchinfo.province_code = ref_provice;
                            mchinfo.city_code = ref_city;
                            mchinfo.area_code = ref_area;
                            mchinfo.machine_address = address;
                            mchinfo.is_sub = false; 
                            successcount++;
                        }
                        catch (Exception ex)
                        {
                            mchinfo.sub_result = ex.ToString();
                            errorcount++;
                        }
                        _tool.di_db.do_rk_Execute(_tool.di_db.AddBySqlStr<mch_settlement>(), mchinfo);
                    } 
                }
                result.code = 0;
                result.msg = "success";
                result.data = new
                {
                    total_mch = mchlist.Count,
                    total_jd_user = jdinfo.Count,
                    successcount,
                    errorcount
                };
                return result;
            });
        }
        /// <summary>
        /// 
        /// </summary>
        public void get_address(JdmerchantBase jd_item, ref int pro, ref int city, ref int area, ref string address)
        {
            if (jd_item != null)
            {
                try
                {
                    string jd_pro = !string.IsNullOrWhiteSpace(jd_item.storeProvince) ? jd_item.storeProvince.Replace("省", "") : "unknow";
                    string jd_city = !string.IsNullOrWhiteSpace(jd_item.storeCity) ? jd_item.storeCity.Replace("市", "") : "unknow";
                    string jd_area = !string.IsNullOrWhiteSpace(jd_item.storeDistrict) ? jd_item.storeDistrict.Replace("区", "") : "unknow";
                    address = jd_item.storeAddress;
                    var pro_result = _face_service.get_area.Where(s => s.name.Contains(jd_pro)).FirstOrDefault();
                    if (pro_result != null)
                    {
                        pro = pro_result.code;
                        var city_result = pro_result.areaList.Any() ? pro_result.areaList.Where(s => s.name.Contains(jd_city)).FirstOrDefault() : null;
                        if (city_result != null)
                        {
                            city = city_result.code;
                            var area_result = city_result.areaList.Any() ? city_result.areaList.Where(s => s.name.Contains(jd_area)).FirstOrDefault() : null;
                            if (area_result != null)
                            {
                                area = area_result.code;
                            }
                            else
                            {
                                area = city_result.areaList.FirstOrDefault().code;
                                address = $"{pro_result.name}{city_result.name}{city_result.areaList.FirstOrDefault().name}";
                            }
                        }
                        else
                        {
                            city = pro_result.areaList.FirstOrDefault().code;
                            area = pro_result.areaList.FirstOrDefault().areaList.FirstOrDefault().code;
                            address = $"{pro_result.name}{pro_result.areaList.FirstOrDefault().name}{pro_result.areaList.FirstOrDefault().areaList.FirstOrDefault().name}";
                        }
                    }
                    else
                    {
                        pro = 120111;
                        city = 120100;
                        area = 120111;
                        address = "天津市华苑产业区（环外）海泰发展三道3号A座5层";
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else {
                pro = 120111;
                city = 120100;
                area = 120111;
                address = "天津市华苑产业区（环外）海泰发展三道3号A座5层";
            }
        }
         
        /// <summary>
        /// 开始运行一个批量的入驻信息
        /// </summary>
        /// <returns></returns>
        public ResultObjModel start_run_ali() {
            return CoreStartDo.ResultAction(result =>
            {
                int success_count = 0;
                int error_count = 0;
                var list = _tool.di_db.Get_rk_List<mch_settlement>("select * from mch_settlement where is_sub=0", null);
                int province_code = 120000;
                int city_code = 120100;
                int area_code = 120111;
                string machine_address = "天津市华苑产业区（环外）海泰发展三道3号A座5层";

                foreach (var item in list)
                {
                    var sub_model = new sub_mch_settlement()
                    {
                        terminal_id = item.mchid,
                        address = new delivery_address_model()
                        {
                            province_code = province_code,
                            city_code = city_code,
                            area_code = area_code,
                            machine_address = machine_address
                        },
                        scene = new scene_model
                        {
                            level_1 = "COMMUNITY",
                            level_2 = "001"
                        }
                    };
                    var ali_result = _face_service.Mch_Settlement(sub_model);
                    if (ali_result.data.Code == "10000")
                    {
                        _tool.di_db.do_rk_Execute("update mch_settlement set ali_terminal_id=@ali_terminal_id,is_sub=@is_sub,sub_params=@sub_params,sub_result=@sub_result,province_code=@province_code,city_code=@city_code,area_code=@area_code,machine_address=@machine_address where mchid=@mchid",
                            new
                            {
                                ali_terminal_id = ali_result.data.AlipayTerminalId,
                                mchid = item.mchid,
                                is_sub = true,
                                sub_params = Newtonsoft.Json.JsonConvert.SerializeObject(sub_model),
                                sub_result = $"{ali_result.data.Msg},{ali_result.data.SubMsg}",
                                province_code = province_code,
                                city_code = city_code,
                                area_code = area_code,
                                machine_address = machine_address
                            });
                        success_count++;
                    }
                    else
                    {
                        _tool.di_db.do_rk_Execute("update mch_settlement set is_sub=@is_sub,sub_params=@sub_params,sub_result=@sub_result,province_code=@province_code,city_code=@city_code,area_code=@area_code,machine_address=@machine_address where mchid=@mchid",
                             new { mchid = item.mchid, is_sub = false, sub_params = Newtonsoft.Json.JsonConvert.SerializeObject(sub_model), sub_result = $"{ali_result.data.Msg},{ali_result.data.SubMsg}",
                                 province_code = province_code,
                                 city_code = city_code,
                                 area_code = area_code,
                                 machine_address = machine_address
                             });
                        error_count++;
                    }
                }
                result.code = 0;
                result.msg = "success";
                result.data = new { success_count, error_count };
                return result;
            });
        }
    }
}
